import { onUnmounted, Ref } from 'vue';
import { onBeforeRouteLeave } from 'vue-router';
import { ElMessageBox } from 'element-plus';
export const useBeforeunload = (type: Ref<boolean>) => {
  const beforeunloadHandel = (event: BeforeUnloadEvent) => {
    if (type.value) {
      event.returnValue = '重新加载此网站?';
    }
  };

  window.addEventListener('beforeunload', beforeunloadHandel);
  onUnmounted(() => {
    window.removeEventListener('beforeunload', beforeunloadHandel);
  });

  onBeforeRouteLeave(async () => {
    if (type.value) {
      const result: boolean = await new Promise((resolve, reject) => {
        ElMessageBox.close();
        ElMessageBox.confirm('当前数据未保存，确定要离开当前窗口?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          draggable: true,
          autofocus: false,
          closeOnHashChange: false,
          closeOnClickModal: false
        })
          .then(() => resolve(true))
          .catch(() => reject(false));
      });
      return result;
    } else {
      return true;
    }
  });
};
